package net.example.activity;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.oraycn.esframework.EsfGlobalUtil;
import com.oraycn.esframework.common.LogonResponse;
import com.oraycn.esframework.core.ClientType;
import com.oraycn.esframework.core.IRapidPassiveEngine;
import com.oraycn.esframework.core.RapidEngineFactory;
import com.oraycn.omcs.MultimediaManagerFactory;
import com.oraycn.omcs.communicate.common.LogonResult;


import net.example.db.DatabaseHelper;
import net.example.manager.ICacheProgressListener;
import net.example.manager.GGApplication;
import net.example.manager.ClientGlobalCache;
import net.example.manager.Manager;
import net.example.model.UserStatus;
import net.example.ggtalk.R;
import net.example.utils.ConfigUtils;
import net.example.utils.IntentUtils;
import net.example.utils.NetUtil;
import net.example.utils.OneKeyExit;
import com.oraycn.esbasic.helpers.StringHelper;

import net.example.utils.ToastUtils;
import net.example.activity.view.CircularProgress;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 登陆模块
 *
 * @author jhz
 */
public class LoginActivity extends BaseActivity {
    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;
    private EditText et_userName, et_passWord, et_serverIP;
    private TextView tv_error_tips;
    private Animation shake;
    private OneKeyExit exit = new OneKeyExit();
    private boolean autoLogin = true;
    private CircularProgress progress;
    private IRapidPassiveEngine engine;
    private Button login_btn;
    private ViewGroup login_tips_panel;
    private SharedPreferences sp_logout;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        initView();
        shake = AnimationUtils.loadAnimation(LoginActivity.this, R.anim.shake);
    }

    /**
     * 初始化控件
     */
    public void initView() {
//        login_btn=(Button)findViewById(R.id.but_postLogin);
//        userName = (EditText) findViewById(R.id.username);
//        passWord = (EditText) findViewById(R.id.password);
//        serverIP = (EditText) findViewById(R.id.ip);
//        progress = (CircularProgress) findViewById(R.id.progress);
        login_btn=(Button)findViewById(R.id.btn_submit);
        et_userName = (EditText) findViewById(R.id.p_id).findViewById(R.id.et_input);
        et_passWord = (EditText) findViewById(R.id.p_newPwd2).findViewById(R.id.et_input);
        et_passWord.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);//设置为密码格式显示 *
        et_serverIP = (EditText) findViewById(R.id.p_ip).findViewById(R.id.et_input);
        et_serverIP.setInputType(InputType.TYPE_CLASS_TEXT);
        et_serverIP.setHint("请输入IP地址");
        et_passWord.setHint("请输入密码");
        et_userName.setHint("请输入用户名");
        ((ImageView) findViewById(R.id.p_ip).findViewById(R.id.iv_ico)).setImageResource(R.drawable.ip_icon);
        ((ImageView) findViewById(R.id.p_id).findViewById(R.id.iv_ico)).setImageResource(R.drawable.user_icon);
        ((ImageView) findViewById(R.id.p_newPwd2).findViewById(R.id.iv_ico)).setImageResource(R.drawable.password_icon);
        ((TextView)findViewById(R.id.p_id).findViewById(R.id.tv_tips)).setVisibility(View.GONE);
        ((TextView)findViewById(R.id.p_newPwd2).findViewById(R.id.tv_tips)).setVisibility(View.GONE);
        ((TextView)findViewById(R.id.p_ip).findViewById(R.id.tv_tips)).setVisibility(View.GONE);
        progress = (CircularProgress) findViewById(R.id.progress);
        tv_error_tips =(TextView)findViewById(R.id.tv_error_tips);
        Context ctx = LoginActivity.this;
        SharedPreferences sp = ctx.getSharedPreferences("loginInfo2", MODE_PRIVATE);
        String host = sp.getString("host", "");
        if (!StringHelper.isNullOrEmpty(host)) {
            et_serverIP.setText(host);
        }
        else {
            et_serverIP.setText(getString(R.string.host));
        }
        String userID=sp.getString("userID", "");
        if(!StringHelper.isNullOrEmpty(userID))
        {
            et_userName.setText(userID);
        }
        String pwd=sp.getString("pwd", "");
        if(!StringHelper.isNullOrEmpty(userID))
        {
            et_passWord.setText(pwd);
        }

        ClientGlobalCache.getInstance().setCacheProgressListener(new ICacheProgressListener() {
            @Override

            public void LoadedProcess(int total, int loaded) {
                Message msg=new Message();
                msg.arg1 = total;
                msg.arg2= loaded;
                msg.what = 10;
                msgHandler.sendMessage(msg);
            }
        });
        sp_logout = ctx.getSharedPreferences("logout", MODE_PRIVATE);
        boolean isLogout=sp_logout.getBoolean("isLogout",false);
        if(!StringHelper.isNullOrEmpty(host)&&!StringHelper.isNullOrEmpty(userID)&&!StringHelper.isNullOrEmpty(userID)&&!isLogout)
        {
            this.Login(null);//自动登陆
        }
    }


    private Handler msgHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    progress.setVisibility(View.VISIBLE);
                    tv_error_tips.setText("正在加载数据...");
                    break;
                case 1:
                    LogonResponse resp = (LogonResponse) msg.obj;
                    tv_error_tips.setText("登录失败:" + resp.getFailureCause());
                    login_btn.setEnabled(true);
                    break;
                case 2:
                    tv_error_tips.setText("已在其他地方登录");
                    login_btn.setEnabled(true);
                    break;
                case 3:
                    tv_error_tips.setText( "客户端与服务端的框架不匹配");
                    login_btn.setEnabled(true);
                    break;
                case 4:
                    tv_error_tips.setText( "连接服务器无响应");
                    login_btn.setEnabled(true);
                    break;
                case 5:
                    com.oraycn.omcs.communicate.common.LogonResponse omcsResp = (com.oraycn.omcs.communicate.common.LogonResponse) msg.obj;
                    if (omcsResp == null) {
                        tv_error_tips.setText( "OMCS连接服务器无响应");
                    } else {

                        tv_error_tips.setText( "登录OMCS失败:" + omcsResp.getFailureCause());
                    }
                    login_btn.setEnabled(true);
                    break;
                case 6:
                    login_btn.setEnabled(true);
                    break;
                case 10:
                    int total=msg.arg1;
                    int loaded=msg.arg2;
                    if(total>0)
                    {
                        tv_error_tips.setText("正在加载数据  "+loaded*100/total+"%");
                    }
                    break;
                case 99:
                    tv_error_tips.setText( "正在登录ESF");
                    break;
                case 100:
                    tv_error_tips.setText( "正在登录OMCS");
                    break;
                case 101:
                    progress.setVisibility(View.INVISIBLE);
                    IntentUtils.startActivityForString(LoginActivity.this, MainActivity.class, "host", et_serverIP.getText().toString());
                    finish();
                    login_btn.setEnabled(true);
                    break;
                case 102:
                    String cause=msg.obj.toString();
                    tv_error_tips.setText(cause);
                    login_btn.setEnabled(true);
                    break;
                default:
                    tv_error_tips.setText( "ESF不明原因登录失败");
                    login_btn.setEnabled(true);
                    break;
            }

            super.handleMessage(msg);
        }
    };

    private void InitData() {
        try {
            DatabaseHelper.resetIntance(engine.getCurrentUserID());
            ClientGlobalCache.getInstance().initialize(engine);
            ClientGlobalCache.getInstance().refreshFriendInfo();
            ConfigUtils.esfServerIP= et_serverIP.getText().toString();
            Manager.getInstance().init(engine);
            Manager.getInstance().changeMyStatus(UserStatus.Online);
            GGApplication.getInstance().setCurrentUser(ClientGlobalCache.getInstance().getCurrentUser());
            GGApplication.getInstance().setEngine(engine);
        } catch (Exception ex) {
            Message msg = new Message();
            msg.obj = "数据初始化失败：" + ex.getMessage();
            msg.what = 102;
            msgHandler.sendMessage(msg);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();

        if (!autoLogin) {
            return;
        }


//        if(getIntent().hasExtra("userName")){
//            progress.setVisibility(View.VISIBLE);
//            new Thread() {
//                @Override
//                public void run() {
//                    loginThread();
//                }
//            }.start();
//        }
    }


private boolean isLogging=false;
    public void Login(View v) {
        if(isLogging){
            return;
        }
        this.isLogging=true;
        login_btn.setEnabled(false);
        progress.setVisibility(View.VISIBLE);

        if (!NetUtil.isNetConnected(this)) {
            login_btn.setEnabled(true);
            this.isLogging=false;
            return;
        }
        if (et_userName.getText().length() == 0) {
            ToastUtils.showShort(this, "用户名不能为空！");
            et_userName.startAnimation(shake);
            login_btn.setEnabled(true);
            this.isLogging=false;
            return;
        }
        if (et_passWord.getText().length() == 0) {
            ToastUtils.showShort(this, "密码不能为空！");
            et_passWord.startAnimation(shake);
            login_btn.setEnabled(true);
            this.isLogging=false;
            return;
        }
        progress.setVisibility(View.GONE);
        new Thread() {
            @Override
            public void run() {
                loginThread();
            }
        }.start();

    }

    private void loginThread() {
        String userID = et_userName.getText().toString();
        //String getPassWord = "pw@12345"; //passWord.getText().toString();
		String getPassWord = StringHelper.md5(et_passWord.getText().toString());
        String serverIP = this.et_serverIP.getText().toString();
        msgHandler.obtainMessage(99).sendToTarget();
        //port 4530
        LogonResponse resp = loginESFramework(serverIP, ConfigUtils.esfServerPort, userID, getPassWord);
        if (resp == null) {
            msgHandler.obtainMessage(6).sendToTarget();
            this.isLogging=false;
            return;
        }
        if (resp.getLogonResult() != com.oraycn.esframework.common.LogonResult.Succeed) {
            msgHandler.obtainMessage(resp.getLogonResult().ordinal(), resp).sendToTarget();
            msgHandler.obtainMessage(6).sendToTarget();
            this.isLogging=false;
            return;
        }

        msgHandler.obtainMessage(100).sendToTarget();
//        "10.52.3.87"  9900  ClientType.ANDROID.getType() + "#" + userID
        com.oraycn.omcs.communicate.common.LogonResponse omcsResp = loginOMCS(serverIP, ConfigUtils.omcsServerPort,ClientType.ANDROID.getType() + "#"+ userID, getPassWord);
        if (omcsResp.getLogonResult() == LogonResult.Succeed) {
            //设置本地摄像头采集分辨率
            MultimediaManagerFactory.GetSingleton().setCameraVideoSize(480, 640);
            //设置视频压缩时质量，数字越小质量越高，须大于0
            MultimediaManagerFactory.GetSingleton().setCameraEncodeQuality(20);

        } else {
            msgHandler.obtainMessage(5, omcsResp).sendToTarget();
            this.isLogging=false;
            return;
        }

        msgHandler.obtainMessage(0).sendToTarget();

        InitData();

        msgHandler.obtainMessage(101).sendToTarget();
        this.isLogging=false;
    }

    private LogonResponse loginESFramework(String esfServerIP, int esfServerPort, String userName, String password) {
        LogonResponse resp = null;
        try {
            engine = RapidEngineFactory.CreatePassiveEngine();
            engine.setEngineEventListener(GGApplication.getInstance());
            engine.getBasicOutter().addBasicEventListener(GGApplication.getInstance());
            engine.setWaitResponseTimeoutInSecs(20);
            Context ctx = LoginActivity.this;
            SharedPreferences sp = ctx.getSharedPreferences("loginInfo2", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("userID", userName);
            editor.putString("pwd", et_passWord.getText().toString());
            editor.putString("host", esfServerIP);
            editor.commit();
            SharedPreferences.Editor editor1= sp_logout.edit().putBoolean("isLogout",false);
            editor1.commit();
            resp = engine.initialize(userName, password, esfServerIP, esfServerPort, GGApplication.getInstance(), getApplication());
        } catch (Exception ex) {
            Message msg = new Message();
            msg.obj = "登录ESF失败：" + ex.getMessage();
            msg.what = 102;
            msgHandler.sendMessage(msg);
        }
        return resp;
    }

    private com.oraycn.omcs.communicate.common.LogonResponse loginOMCS(String omcsServerIP, int omcsServerPort, String userName, String password) {
        com.oraycn.omcs.communicate.common.LogonResponse omcsResp = null;
        try {
            //MultimediaManagerFactory.GetSingleton().getAdvanced().setAmplifier4AudioPlay(2);//放大声音
            omcsResp = MultimediaManagerFactory.GetSingleton().initialize(userName,
                    password, omcsServerIP, omcsServerPort, getApplication());
        } catch (Exception ex) {
            Message msg = new Message();
            msg.obj = "登录OMCS失败：" + ex.getMessage();
            msg.what = 102;
            msgHandler.sendMessage(msg);
        }
        return omcsResp;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();
        }
        return false;
    }

    private void exitBy2Click() {
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            Timer tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }
    public void register(View view)
    {
//        ToastUtils.showShort(this,"功能暂未开通");
        String serverIp= et_serverIP.getText().toString();
        Intent intent=new Intent(this,RegisterActivity.class);
        intent.putExtra(getString(R.string.host), et_serverIP.getText().toString());
        if(!StringHelper.isNullOrEmpty(serverIp))
        {
            ConfigUtils.esfServerIP=serverIp;
        }
        startActivityForResult(intent, 0);
    }

    public void copyQQ(View v)
    {
        if(this.copyStr("10000")){
            ToastUtils.showShort(this,"号码已复制");
        }
    }

    public void openUrl(View v){
        Intent intent = new  Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri uri = Uri.parse("https://www.googel.com");
        intent.setData(uri);
        startActivity(intent);
    }

    /**
     * 复制内容到剪切板
     *
     * @param copyStr
     * @return
     */
    private boolean copyStr(String copyStr) {
        try {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", copyStr);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode != RESULT_OK) {
            return;
        }
        if(requestCode==0)
        {
            String userID=intent.getStringExtra(getString(R.string.userID));
            this.et_userName.setText(userID);
            this.et_passWord.setText("");
            ToastUtils.showLong(this,String.format("注册成功！您的帐号为%s,您可以使用此帐号登录",userID));
        }
    }
}